const { query, beginTransaction, commitTransaction, rollbackTransaction } = require('../config/db');

class UserAddress {
  /**
   * 根据用户ID获取地址列表
   * @param {number} userId - 用户ID
   * @returns {Promise<Array>} 地址列表
   */
  static async getByUserId(userId) {
    try {
      const addresses = await query(
        'SELECT * FROM user_addresses WHERE user_id = ? ORDER BY is_default DESC, created_at DESC',
        [userId]
      );
      return addresses;
    } catch (error) {
      console.error('获取用户地址列表失败:', error);
      throw error;
    }
  }

  /**
   * 根据ID获取地址详情
   * @param {number} id - 地址ID
   * @param {number} userId - 用户ID（用于权限验证）
   * @returns {Promise<Object|null>} 地址信息
   */
  static async findById(id, userId) {
    try {
      const addresses = await query(
        'SELECT * FROM user_addresses WHERE id = ? AND user_id = ?',
        [id, userId]
      );
      return addresses.length > 0 ? addresses[0] : null;
    } catch (error) {
      console.error('获取地址详情失败:', error);
      throw error;
    }
  }

  /**
   * 创建新地址
   * @param {Object} addressData - 地址数据
   * @returns {Promise<Object>} 创建的地址信息
   */
  static async create(addressData) {
    const connection = await beginTransaction();
    
    try {
      const {
        user_id, recipient_name, phone_number, province, city, district,
        detailed_address, is_default = false
      } = addressData;

      // 如果设置为默认地址，先将该用户的其他地址设为非默认
      if (is_default) {
        await connection.execute(
          'UPDATE user_addresses SET is_default = FALSE WHERE user_id = ?',
          [user_id]
        );
      }

      // 创建新地址
      const [result] = await connection.execute(`
        INSERT INTO user_addresses (
          user_id, recipient_name, phone_number, province, city, district,
          detailed_address, is_default
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
      `, [
        user_id, recipient_name, phone_number, province, city, district,
        detailed_address, is_default
      ]);

      await commitTransaction(connection);

      // 返回创建的地址信息
      return await this.findById(result.insertId, user_id);
    } catch (error) {
      await rollbackTransaction(connection);
      console.error('创建地址失败:', error);
      throw error;
    }
  }

  /**
   * 更新地址
   * @param {number} id - 地址ID
   * @param {number} userId - 用户ID
   * @param {Object} addressData - 更新的地址数据
   * @returns {Promise<Object>} 更新后的地址信息
   */
  static async update(id, userId, addressData) {
    const connection = await beginTransaction();
    
    try {
      const {
        recipient_name, phone_number, province, city, district,
        detailed_address, is_default = false
      } = addressData;

      // 检查地址是否存在且属于该用户
      const existingAddress = await this.findById(id, userId);
      if (!existingAddress) {
        throw new Error('地址不存在或无权限访问');
      }

      // 如果设置为默认地址，先将该用户的其他地址设为非默认
      if (is_default) {
        await connection.execute(
          'UPDATE user_addresses SET is_default = FALSE WHERE user_id = ? AND id != ?',
          [userId, id]
        );
      }

      // 更新地址
      await connection.execute(`
        UPDATE user_addresses SET
          recipient_name = ?, phone_number = ?, province = ?, city = ?, district = ?,
          detailed_address = ?, is_default = ?
        WHERE id = ? AND user_id = ?
      `, [
        recipient_name, phone_number, province, city, district,
        detailed_address, is_default, id, userId
      ]);

      await commitTransaction(connection);

      // 返回更新后的地址信息
      return await this.findById(id, userId);
    } catch (error) {
      await rollbackTransaction(connection);
      console.error('更新地址失败:', error);
      throw error;
    }
  }

  /**
   * 删除地址
   * @param {number} id - 地址ID
   * @param {number} userId - 用户ID
   * @returns {Promise<boolean>} 删除结果
   */
  static async delete(id, userId) {
    try {
      // 检查地址是否存在且属于该用户
      const existingAddress = await this.findById(id, userId);
      if (!existingAddress) {
        throw new Error('地址不存在或无权限访问');
      }

      const result = await query(
        'DELETE FROM user_addresses WHERE id = ? AND user_id = ?',
        [id, userId]
      );

      return result.affectedRows > 0;
    } catch (error) {
      console.error('删除地址失败:', error);
      throw error;
    }
  }

  /**
   * 设置默认地址
   * @param {number} id - 地址ID
   * @param {number} userId - 用户ID
   * @returns {Promise<Object>} 更新后的地址信息
   */
  static async setDefault(id, userId) {
    const connection = await beginTransaction();
    
    try {
      // 检查地址是否存在且属于该用户
      const existingAddress = await this.findById(id, userId);
      if (!existingAddress) {
        throw new Error('地址不存在或无权限访问');
      }

      // 将该用户的所有地址设为非默认
      await connection.execute(
        'UPDATE user_addresses SET is_default = FALSE WHERE user_id = ?',
        [userId]
      );

      // 设置指定地址为默认
      await connection.execute(
        'UPDATE user_addresses SET is_default = TRUE WHERE id = ? AND user_id = ?',
        [id, userId]
      );

      await commitTransaction(connection);

      // 返回更新后的地址信息
      return await this.findById(id, userId);
    } catch (error) {
      await rollbackTransaction(connection);
      console.error('设置默认地址失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户的默认地址
   * @param {number} userId - 用户ID
   * @returns {Promise<Object|null>} 默认地址信息
   */
  static async getDefaultAddress(userId) {
    try {
      const addresses = await query(
        'SELECT * FROM user_addresses WHERE user_id = ? AND is_default = TRUE',
        [userId]
      );
      return addresses.length > 0 ? addresses[0] : null;
    } catch (error) {
      console.error('获取默认地址失败:', error);
      throw error;
    }
  }
}

module.exports = UserAddress;
